/* eslint-disable */
/**
 * Created by GYL on 2018/8/24
 */
import React, { Component } from 'react';
import styles from '../EventPosting.less';
import { Collapse, Icon, Select, Input, Tooltip, Form, Row, Col, TreeSelect, Tag, message, Popconfirm, Tree, Spin, Radio, Upload, Button } from 'antd';
import PublicService from "../../../services/PublicService";
import config from '../../../config';
import Util from '../../../utils/Util';
import request from '../../../utils/request';
import MyTable from "../../../components/common/MyTable";
import MyModal from '../../../components/common/MyModal';
import moment from 'moment';
const { Panel } = Collapse;
const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
const { SHOW_CHILD } = TreeSelect;
const { TreeNode } = Tree;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_1315525_kt2bd7ytf.js',
});
var flag = false
class Edit_Appeal extends Component {
    state = {
        treeData: [],
        TreeSelect: [],
        dataSource: [],
        dataArr: [
        ],
        spinning: false,
        value: '',
        columns: [
            {
                title: '序号',
                dataIndex: 'num',
                width: '5%',
                align: "center",
                render: (text, record, index) => {
                    return <span>
                        {index + 1}
                    </span>

                }
            },
            {
                title: '文件名',
                dataIndex: 'fileName',
                width: '20%',
                align: "center",
            },
            {
                title: "文件类型",
                dataIndex: 'fileType',
                width: '15%',
                align: "center",
            },
            {
                title: '文件大小',
                width: '10%',
                dataIndex: 'fileSize',
                align: "center",
            },
            {
                title: '上传时间',
                width: '20%',
                dataIndex: 'createTime',
                align: "center",
                render: (text, record) => {
                    return <span>
                      {record.createTime?moment(record.createTime).format('YYYY-MM-DD HH:mm:ss'):''}
                    </span>
                }
            },
            {
                title: '上传人',
                width: '15%',
                dataIndex: 'uploadUser',
                align: "center",

            },
            {
                title: '操作',
                width: '10%',
                dataIndex: 'uploadUs123er',
                align: "center",
                render: (text, record) => {
                    return <span>
                        <Popconfirm
                            title="确定删除此条数据?"
                            onConfirm={this.confirm.bind(this, record)}
                            onCancel={this.cancel}
                            okText="是"
                            cancelText="否"
                        >
                            <a href="javascript:;" >删除</a>
                        </Popconfirm>
                    </span>

                }
            },
        ],
        arr: [
            {
                type: 'TextArea',
                paramName: 'repositoryName',
                id: 'repositoryName',
                title: '0/30',
                num: 30,
                key: "repositoryName",
                label: '知识库名称',
                style: { width: 400 },
                rules: [{ ...config.reg.required }],
                span: 12,
                rows: 3,
            },

            {
                type: 'TextArea',
                paramName: 'content',
                id: 'content',
                title: '0/500',
                num: 500,
                key: "content",
                label: '知识库内容',
                style: { width: 400 },
                rules: [{ ...config.reg.required }],
                span: 12,
                rows: 3,
            },
            {
                type: 'Upload',
                label: '仅支持预览doc、docx、pdf、jpg、png、xls、xlsx,最大限制为20MB',
                paramName: 'Upload',
            },
            {
                type: 'Button',
            },



        ],
    };

    componentDidMount() {

        this.submitChangeApprovalTwo()

        this.getAllUserTreeByProjectId()
    }

    confirm = (record) => {

        this.onDelete(record)
    }

    cancel = (e) => {

    }

    //查询项目审批人员
    getAllUserTreeByProjectId = () => {
        request({
            url: '/pm-web/projectmanage/projectinfo/getAllUserTreeByProjectId',
            method: 'POST',
            data: { projectId: this.props.id }
        }).then(data => {
            if (data.rc === 0)[
                this.setState({
                    treeData: data.ret
                })
            ]
        })
    }

    //查询事件知识库
    submitChangeApprovalTwo = () => {
        request({
            url: '/pm-web/projectmanage/progress/submitChangeApprovalTwo',
            method: 'POST',
            data: { projectId: this.props.id, changeId: this.props.changeId }
        }).then(data => {
            // console.log(data)
            if (data.rc === 0) {
                this.setState({
                    dataArr: data.ret.resultList,
                    value: data.ret.resultList[0].uuid
                })
                //查询知识库文件
                request({
                    url: '/pm-web/projectmanage/knowledgebase/getFileList',
                    method: 'POST',
                    data: { parentId: data.ret.resultList[0].uuid, tableName: 'ta_uf_event_info' }
                }).then(data => {
                    if (data.rc === 0) {
                        this.setState({
                            dataSource: data.ret.fileList
                        })
                    }
                })

            }
        })
    }

    //查询知识库文件列表
    getFileList = (id) => {
        request({
            url: '/pm-web/projectmanage/knowledgebase/getFileList',
            method: 'POST',
            data: { parentId: id, tableName: 'ta_uf_event_info' }
        }).then(data => {
            if (data.rc === 0) {
                this.setState({
                    dataSource: data.ret.fileList
                })
            }
        })
    }

    onChange = e => {
        // console.log('radio checked', e.target.value);
        this.props.form.resetFields();//重置from表单所有值
        this.setState({
            value: e.target.value,
        }, () => {
            this.onsaveSc()
        });


        this.state.dataArr.forEach((item) => {
            if (item.uuid == e.target.value) {
                this.props.form.setFieldsValue({ 'repositoryName': item.repositoryName ? item.repositoryName : '' })
                this.props.form.setFieldsValue({ 'content': item.content ? item.content : '' })
            }
        })




    };


    //计算文本域内数字个数
    onChangeNum = (v) => {
        var strs = getByteLen(v);
        function getByteLen(val) {
            strs = val.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\，|\。|\？|\：|\；|\‘|\’|\”|\“|\、|\·|\！|\（|\）|\》|\《|\『|\』]/g, "");
            return strs;
        }
        return strs.length

    }
    // 取消保存
    ModalCancel = (type) => {
        let t = this;
        t.setState({
            [type]: false,
            modalBtnLoading: false
        })
    };



    // 筛选条件组件change事件
    getChangeValue = (value, e) => {
        let t = this;
        let params = {};
        params[value] = e.target.value;
        t.setState({ params });
        //form表单赋值-----改变文本域数字个数
        this.props.form.setFieldsValue({ [value]: e.target.value })
        this.addChange(value, e.target.value.length)


    }



    getChangeValueList = (value, e) => {
        let t = this;
        let params = {};
        params[value] = e.target.value;
        t.setState({ params });
        //form表单赋值-----改变文本域数字个数
        this.props.form.setFieldsValue({ [value]: e.target.value })
        this.addChangeList(value, e.target.value.length)


    }

    addChangeList = (v, num) => {
        this.state.arr[10].list.forEach(item => {
            if (item.paramName === v) {
                item.title = `${num}/${item.num}`
            }
        });
    }

    addChangeSon = (v, num, index) => {
        this.state.sonArr[index].sonArrList.forEach(item => {
            if (item.paramName === v) {
                item.title = `${num}/${item.num}`
            }
        });
    }
    //新增改变tooplie的显示文字
    addChange = (v, num) => {
        this.state.arr.forEach(item => {
            if (item.paramName === v) {
                item.title = `${num}/${item.num}`
            }
        });
    }

    //保存按钮事件
    onModalSave = () => {
        this.props.form.validateFields((errors, values) => {
            if (!errors) {
                // console.log(values)
                this.state.dataArr.forEach((item) => {
                    //判断当前选中的id 保存进入事件数组
                    if (item.uuid == this.state.value) {
                        item.repositoryName = values.repositoryName
                        item.content = values.content
                        item.flag = true
                        item.nickName = PublicService.getCookie('nickName')

                    }
                })
                message.success('保存成功')
            }
        });

    }


    selectedChange(fun, nextParams, paramName, index, value) {
        // console.log(fun, nextParams, paramName, index, value)


        let t = this;
        let params = {};
        params[paramName] = value;
        if (paramName) {
            t.setState({ params }, () => {
            });
        }
        if (typeof fun === "function") {
            fun(value);
            if (nextParams)
                t.props.form.setFieldsValue({
                    [nextParams]: ''
                })
        }
    }


    onBack = () => {
        this.props.onBackAppeal()
    }


    onChangeTreeSelect = value => {
        // console.log(value);
        this.setState({ TreeSelect: value });
    };

    //提交
    onSumit = () => {


        let flagnum = 1;

        this.state.dataArr.forEach((item) => {
            if (!item.flag) {
                flagnum++;
            }
        })

        if (flagnum != 1) {
            message.warning('请核对所有事件完成后提交!')
            return
        }

        if (this.state.TreeSelect < 1) {
            message.warning('请选择审批人员后提交!')
            return
        }
        this.setState({
            spinning:true
        })

        let params = {
            changeId: this.props.changeId,
            projectId: this.props.id,
            userId: PublicService.getCookie('userId'),
            verifierList: this.state.TreeSelect,
            zskList: this.state.dataArr
        }

        request({
            url: '/pm-web/projectmanage/progress/submitChangeApprovalThree',
            method: 'POST',
            data: params
        }).then(data => {
            if (data.rc === 0) {
                message.success('操作成功!')
                this.props.onBackAll()
            } else {
                message.warning(`${data.err}`)
            }
            this.setState({
                spinning: false
            })
        })

    }




    //上传
    onsc = (info) => {
        if (info.file.status !== 'uploading') {
        }
        if (info.file.status === 'done') {
            message.success(`${info.file.name} 上传成功`);
            this.onsaveSc()
            this.getFileList()


        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 上传失败.`);
        }
    }

    //查询上传附件
    onsaveSc = () => {
        request({
            url: `/pm-web/projectmanage/knowledgebase/getFileList`,
            method: 'POST',
            data: { parentId: this.state.value, tableName: 'ta_uf_event_KnowledgeBase' }
        }).then(data => {
            // console.log(data)
            if (data.rc == 0) {

                this.setState({
                    dataSource: data.ret.fileList
                })
            }
        })
    }
    //bianji查询上传附件
    getFileList = () => {
        request({
            url: `/pm-web/projectmanage/knowledgebase/getFileList`,
            method: 'POST',
            data: { parentId: this.state.value, tableName: 'ta_uf_event_KnowledgeBase' }
        }).then(data => {
            // console.log(data)
            if (data.rc == 0) {

                this.setState({
                    dataSource: data.ret.fileList
                })
            }
        })
    }

    //删除上传文件
    onDelete = (record) => {
        // console.log(record)
        request({
            url: `/pm-web/projectmanage/fileupload/deleteFile?id=${record.id}`,
            method: 'GET',
        }).then(data => {
            if (data.rc == 0) {
                message.success('删除成功');
                this.onsaveSc()
            }
        })
    }






    render() {
        let t = this
        let width = document.body.clientWidth;
        const height = document.body.clientHeight;
        let containerHeight = '76vh';
        let tableHeight = 310;
        if (width > 1367) {
            tableHeight = 380;
            containerHeight = '83vh';
        }
        const radioStyle = {
            display: 'block',
            height: '30px',
            lineHeight: '30px',
            width: '100%',
            marginTop: '10px'
        };
        const { getFieldDecorator } = this.props.form;
        const props1 = {
            name: 'file',
            action: '/pm-web/projectmanage/fileupload/dopost',

            headers: {
                authorization: 'authorization-text',
            },
            data: {
                pid: this.state.value,
                tableName: "ta_uf_event_KnowledgeBase",
                uploadUser: PublicService.getCookie('nickName'),
            },
            multiple: true,
            showUploadList: true

        };


        return (
            <Spin tip="Loading..." spinning={this.state.spinning}>
                <div style={{ margin: 10, marginBottom: 0, marginTop: 0, height: '86vh', backgroundColor: '#F6FCFC', boxShadow: "0px 0px 4px 0px rgba(223,223,223,1)", borderRadius: 3 }}>
                    <div style={{ height: '30px', backgroundColor: '#D6EDEB', display: 'flex', alignItems: 'center', flexDirection: 'row', borderRadius: 3, border: '2px solid #fff', paddingLeft: 15 }}>提交审批</div>
                    <div className={styles.warpBox} style={{ height: '76vh', backgroundColor: '#F6FCFC', overflow: 'auto' }}>

                        <div style={{ flex: 1, backgroundColor: '#f6f6f18a', overflow: 'auto', display: 'flex' }}>
                            <div style={{ flex: 1, display: 'flex', alignItems: 'center', flexDirection: 'column', overflow: 'auto', height: '76vh' }}>
                                <div style={{ fontSize: 14, fontWeight: 700, textAlign: 'center', width: '100%', boxShadow: "0px 0px 4px 0px rgba(223,223,223,1)", borderRadius: 3, backgroundColor: '#fff', marginTop: 3 }}>必填事件</div>
                                <div style={{ flex: 1, overflow: 'auto', maxHeight: '76vh', borderRadius: 3, backgroundColor: '#fff', boxShadow: "0px 0px 4px 0px rgba(223,223,223,1)", margin: 3, width: '100%', padding: 5 }}>
                                    <Radio.Group onChange={this.onChange} value={this.state.value} style={{ width: '100%' }}>
                                        {
                                            this.state.dataArr.map((item) => {
                                                return (
                                                    <Radio style={radioStyle} value={item.uuid}>
                                                        {item.eventName} <span style={{ float: 'right' }}>{item.flag ? '已配置' : '未配置'}</span>
                                                    </Radio>
                                                )
                                            })
                                        }



                                    </Radio.Group>
                                </div>

                            </div>
                            <div style={{ width: 15, display: 'flex', alignItems: 'center', flexDirection: 'column', backgroundColor: '#f7f5f5', justifyContent: 'space-around' }}>


                            </div>


                            <div style={{ flex: 4, display: 'flex', alignItems: 'center', flexDirection: 'column', overflow: 'auto', height: '76vh' }}>

                                <div style={{ flex: 1, overflow: 'auto', maxHeight: '76vh', borderRadius: 3, backgroundColor: '#fff', boxShadow: "0px 0px 4px 0px rgba(223,223,223,1)", margin: 3, width: '100%' }}>

                                    <div style={{ paddingLeft: 40, marginTop: 10 }}>
                                        <p><span style={{ color: 'red' }}>* </span>审批人员 : </p>
                                        <TreeSelect
                                            style={{ width: 400 }}
                                            value={this.state.TreeSelect}
                                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                            treeData={this.state.treeData}
                                            placeholder="请选择"
                                            treeDefaultExpandAll
                                            onChange={this.onChangeTreeSelect}
                                            treeCheckable={true}
                                            showCheckedStrategy={SHOW_CHILD}

                                        />
                                    </div>

                                    <Form style={{ paddingLeft: 40, paddingRight: 40 }} >
                                        <Row gutter={48} key={55555}>
                                            {
                                                this.state.arr.map((item, index) => {
                                                    if (item.type === 'TextArea') {
                                                        return (
                                                            <Col span={item.span || 8} key={index} className={item.className}>
                                                                <Form.Item label={item.label} key={item.paramName}>
                                                                    <Tooltip
                                                                        trigger={['focus']}
                                                                        title={item.title}
                                                                        placement="topLeft"
                                                                        overlayClassName="numeric-input"
                                                                    >
                                                                        {
                                                                            getFieldDecorator(item.paramName, {
                                                                                initialValue: item.initialValue ? item.initialValue : '',
                                                                                rules: item.rules || null
                                                                            })(

                                                                                <TextArea
                                                                                    style={item.style}
                                                                                    placeholder={item.placeholder}
                                                                                    // onChange={this.onChange}
                                                                                    className={item.shuoming}
                                                                                    rows={item.rows}
                                                                                    maxLength={item.num}
                                                                                    disabled={item.disabled} id={[item.paramName]}
                                                                                    onChange={this.getChangeValue.bind(this, item.paramName)} size={config.size}
                                                                                />

                                                                            )
                                                                        }
                                                                    </Tooltip>
                                                                </Form.Item>
                                                            </Col>
                                                        )
                                                    }
                                                    if (item.type === 'Upload') {
                                                        return (
                                                            <Col key={index} span={item.span || 12} offset={item.offset}>
                                                                <FormItem colon={false} label={item.label} >
                                                                    {
                                                                        getFieldDecorator(item.paramName, {
                                                                            initialValue: item.initialValue || "",
                                                                            rules: item.rules || null,
                                                                        })(

                                                                            <Upload {...props1} onChange={this.onsc}>
                                                                                <div style={{

                                                                                    cursor: 'pointer'
                                                                                }}>
                                                                                    <IconFont type="icon-wenjianshangchuan" style={{ fontSize: 25 }} />
                                                                                    上传文件

                                                                            </div>
                                                                            </Upload>

                                                                        )
                                                                    }
                                                                </FormItem>
                                                            </Col>
                                                        )
                                                    }
                                                    if (item.type === 'Button') {
                                                        return (
                                                            <Col key={index} span={item.span || 12} offset={item.offset}>
                                                                <div style={{ color: '#fff', width: 136, height: 25, background: 'rgba(0,171,187,1)', borderRadius: 4, textAlign: 'center', lineHeight: '25px', cursor: 'pointer', marginTop: 50 }} onClick={this.onModalSave}>保存</div>
                                                            </Col>
                                                        )
                                                    }

                                                })
                                            }

                                        </Row>
                                    </Form>

                                    <MyTable
                                        pagination={false}
                                        columns={this.state.columns}
                                        dataSource={this.state.dataSource}
                                    />
                                </div>
                            </div>

                        </div>
                    </div>
                    <div className={styles.Bottom_Box} style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center', height: '7vh' }}>
                        <div style={{ color: '#fff', width: 136, height: 32, background: 'rgba(0,171,187,1)', borderRadius: 14, textAlign: 'center', lineHeight: '32px', cursor: 'pointer' }} onClick={this.onSumit}>提交</div>

                        <div style={{ color: 'red', width: 136, height: 32, background: '#fff', borderRadius: 14, textAlign: 'center', lineHeight: '32px', border: '1px solid #ccc', cursor: 'pointer' }} onClick={this.onBack}>关闭</div>
                    </div>
                </div>
            </Spin>
        );


    }
}
export default Form.create()(Edit_Appeal);

